#include <stdio.h>
#include <stdlib.h>
#include <mqueue.h>

#include "stockage.h"
#include "ResChaineCond.h"
#include "partage_stock_ret.h"
#include "../utils/utils.h"
#include "../interface/messqueue.h"
#include "../interface/variablesglobales.h"


static mqd_t bal_messages;
static mqd_t bal_palettes;

static unsigned short continuer = 1;

void init_stockage_compteurs() {
	g_compteur_stock[0] = 0;
	g_compteur_stock[1] = 0;
}

void init_mutex_stock() {
	pthread_mutex_init(&mut_stock, NULL);
}
/**
 Initialisation de la tache
*/
void init_stockage() {
	// debug
	printf("[Stockage] Coucou le stockage \n");
	init_stockage_compteurs();
	init_mutex_stock();
	bal_messages = ouvrir_mqueue(BAL_MESSAGES_NAME, O_WRONLY);
	bal_palettes = ouvrir_mqueue(BAL_PALETTES_NAME, O_RDONLY);
}
/**
 Destruction des ressources utilisées
*/
void detruire_stockage() {
	mq_close(bal_messages);
	mq_close(bal_palettes);
}

void* stockage(void* parameter) {
	// non utilisé
	(void) parameter;
	init_stockage();

	while(continuer) {
		struct message msg_recu;

		int taille_lue = lire_message(bal_palettes, &msg_recu);
		if (taille_lue == -1) {
			perror("[Stockage] Echec lire_message");
			exit(1);
		}

		if(msg_recu.type == ARRET) {
			// debug
			printf("[Stockage] Arrêt complet\n");
			struct message msg_pal_fin;
			msg_pal_fin.type = ARRET;

			mq_send (bal_messages, (char *)&msg_pal_fin, sizeof(struct message), 1);
			break;
		}

		int type_piece = msg_recu.params[1];

		printf("[Stockage] Palette reçue: type: %d \n", type_piece);

		pthread_mutex_lock(&mut_stock);

		g_compteur_stock[type_piece]++;

		pthread_mutex_unlock(&mut_stock);

		//debug
		printf("[Stockage] stock++: %d\n", g_compteur_stock[type_piece]);
		struct message msg_stock;
		msg_stock.type = STOCKOK;
		msg_stock.params[0] = msg_recu.params[0];
		msg_stock.params[1] = msg_recu.params[1];
		msg_stock.params[2] = msg_recu.params[2];

		mq_send (bal_messages, (char *)&msg_stock, sizeof(struct message), 1);

		
	}

	detruire_stockage();
	return 0;
}

void vider_bal_palettes() {
	vider_bal(bal_palettes);
}
